package com.ticket.sass.common.ticketserver

import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.ticket.sass.common.ticketserver.exceptions.ParseDataException
import java.math.BigDecimal
import java.text.DecimalFormat
import java.time.*
import java.time.format.DateTimeFormatter


// 字符串处理
fun String.isBool(): Boolean {
    return this == "true" || this == "false"
}
fun String.toBool(): Boolean? {
    return when(this) {
        "true" -> true
        "false" -> false
        else -> null
    }
}
fun String.toJson(): Map<*, *>? {
    return try {
        Gson().fromJson(this, Map::class.java)
    } catch (e: Exception) {
        null
    }
}
fun String.toLocalDateTime(pattern: String): LocalDateTime {
    return LocalDateTime.parse(this, DateTimeFormatter.ofPattern(pattern))
}
fun String.timestampToLocalDateTime(): LocalDateTime {
    val instant = Instant.ofEpochSecond(this.toLong());
    return instant.atZone(ZoneId.systemDefault()).toLocalDateTime()
}
fun String.toLocalDate(pattern: String): LocalDate {
    return LocalDate.parse(this, DateTimeFormatter.ofPattern(pattern))
}

fun <T>String.parseJson(model: Class<T>): T {
    return try {
        Gson().fromJson(this, model)
    } catch (e: JsonSyntaxException) {
        e.printStackTrace()
        throw ParseDataException("1", e.message)
    }
}

// 时间处理
fun LocalDateTime.format(pattern: String): String {
    return DateTimeFormatter.ofPattern(pattern).format(this)
}
fun LocalDateTime.toTimestamp(): Long {
    return this.toInstant(ZoneOffset.ofHours(8)).toEpochMilli()
}
fun DayOfWeek.format(): String {
    val week = when (this.toString()) {
        "MONDAY" -> "一"
        "TUESDAY" -> "二"
        "WEDNESDAY" -> "三"
        "THURSDAY" -> "四"
        "FRIDAY" -> "五"
        "SATURDAY" -> "六"
        "SUNDAY" -> "日"
        else -> ""
    }

    return "周$week"
}

// map 处理
fun Map<*, *>.formatString(): String {
    return Gson().toJson(this)
}

fun<T> T.toJson(): String {
    return Gson().toJson(this)
}

// BigDecimal 处理
fun BigDecimal.formatString(pattern: String, scale: Int): String {
    return DecimalFormat(pattern).format(this.setScale(scale, BigDecimal.ROUND_DOWN))
}